<template>
  <div class="df-upload-image" style="position: relative">
    <n-upload
      v-if="!temUrl && routerType !== 'check'"
      ref="upload"
      :multiple="false"
      :headers="headers"
      :accept="props.fileType.map((a) => `.${a}`).join(',')"
      list-type="image-card"
      :custom-request="customRequest"
      :max="max"
      @before-upload="beforeUpload"
    >
      <div class="upload-add-img">
        <i class="n-base-icon"
          ><svg
            width="512"
            height="512"
            viewBox="0 0 512 512"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M256 112V400M400 256H112"
              stroke="currentColor"
              stroke-width="32"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
        </i>
      </div>
    </n-upload>
    <span v-if="!temUrl && routerType === 'check'" style="line-height: 80px">-</span>
    <div v-if="temUrl" class="upload-img">
      <n-image object-fit="cover" class="imageclass" :src="temUrl" />

      <div class="icon-img">
        <n-space>
          <n-icon
            :size="18"
            :component="EyeOutlined"
            @click="
              () => {
                showModal = true;
              }
            "
          />
          <n-icon
            v-if="routerType !== 'check'"
            :size="18"
            :component="DeleteOutlined"
            @click="
              () => {
                temUrl = '';
                emit('responseImg', {
                  fileUrl: '',
                  fileName: '',
                });
              }
            "
          />
          <!-- <n-icon :size="18" :component="ArrowDownOutlined" @click="handleDownPic" /> -->
        </n-space>
      </div>
    </div>

    <div class="notice" v-if="showNotice">{{
      t('notice', { msg: props.fileType.join('、') })
    }}</div>
    <n-modal v-model:show="showModal" preset="card" style="width: 600px" :title="'预览'">
      <n-image class="" width="600" :src="temUrl" />
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  // import { getTemUrl } from '@/api/common/index';
  // import useLang from '@/hooks/useLang';
  import { storage } from '@/utils/Storage';
  import i18n from '@/i18n';
  import {
    DeleteOutlined,
    EyeOutlined,
    // ArrowDownOutlined
  } from '@vicons/antd';
  import { useMixins } from '@/hooks/useMixins';
  import { fileUpload } from '@/api/common';
  // import { downLoadFile } from '@/api/basicConfiguration/deviceInfo';
  // import config from '@/config';
  // import { downloadFile as downloadFile2 } from '@/utils/downloadFile';

  // const {  VUE_APP_BASE_URL } = config;
  const { language } = useMixins();
  const { routerType } = useMixins();

  const emit = defineEmits(['responseImg']);
  // console.log(['2', '5'].join(','));
  const { t, mergeLocaleMessage } = i18n.global;
  const messages = {
    zh_cn: {
      tip: '文件格式错误，请上传 {msg} 格式的文件',
      notice: '仅支持{msg}文件格式',
    },
    en_us: {
      tip: 'File format error, please upload {msg} Format file',
      notice: 'Only supported{msg}file format',
    },
  };
  mergeLocaleMessage('en', messages.en_us);
  mergeLocaleMessage('zh', messages.zh_cn);
  // const { t } = useLang({ messages, path: 'UploadImage' });

  const message = window['$message'];
  type Props = {
    width?: string;
    fileUrl?: string | null;
    fileType?: string[];
    showNotice?: boolean;
    fileName?: string;
    maxSize?: number;
    max?: number;
  };

  const props = withDefaults(defineProps<Props>(), {
    width: () => '80',
    fileUrl: () => '',
    fileType: () => ['bmp', 'jpg', 'png'],
    showNotice: () => false,
    fileName: () => '',
    maxSize: () => 10,
    max:()=>10
  });

  // const previewFileList = ref([]);

  // const api = import.meta.env.VITE_GLOB_API_URL;
  async function customRequest({ file, onFinish, onError }) {
    const form = new FormData();
    form.append('file', file.file as string | Blob);

    const res = await fileUpload(form);

    const { code, data } = res;

    if (code === 200) {
      onFinish();

      // previewFileList.value.push({
      //   status: 'finished',
      //   url: data.url,
      // });

      emit('responseImg', {
        fileUrl: data.url,
        fileName: file.name,
      });

      // console.log(previewFileList.value)
    } else {
      onError();
    }

    // console.log(res);
  }

  const headers = {
    authorization: 'Bearer ' + storage.get('access_token') || '',
    'login-id': storage.getCookie('login-id') || '',
    language: language.value == 'zh' ? 'zh-cn' : 'en_us',
    'tenant-code': storage.getCookie('tenant-code') || '',
  };

  // type ResImg = {
  //   realUrl: string;
  //   temUrl: string;
  // };

  let showModal = ref(false);
  // let realUrl = ref('');
  let temUrl = ref('');
  const width = computed(() => {
    return `${props.width}px`;
  });

  //上传前检验
  const beforeUpload = (file) => {
    // 设置最大值，则判断
    if (props.maxSize && file.file.file.size / 1024 / 1024 >= props.maxSize) {
      message.error(`上传文件大小不能超过${props.maxSize}MB`);
      return false;
    }
    let fileExtension = '';
    if (file.file.name.lastIndexOf('.') > -1) {
      fileExtension = file.file.name.slice(file.file.name.lastIndexOf('.') + 1).toLowerCase();
    }
    const isTypeOk = props.fileType.some((type) => {
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      message.error(t('tip', { msg: props.fileType.join('、') }));
      return false;
    }
    return true;
  };
  //获取临时文件
  const getTemUrlData = (url) => {
    if (url?.indexOf('http') != -1) {
      temUrl.value = url;
    } else if (url) {
      temUrl.value = `http://${storage.get('host')}:3000/file/${url}`;
    } else {
      temUrl.value = '';
    }
  };
  watch(
    [props],
    () => {
      props.fileUrl && getTemUrlData(props.fileUrl);
    },
    { immediate: true, deep: true }
  );
  //上传完成的回调
  // const handleFinish = (e: any) => {
  //   console.log(e);
  //   try {
  //     const response = JSON.parse(e.event.currentTarget.response);
  //     realUrl.value = response.row.realUrl;
  //     temUrl.value = response.row.temUrl;
  //     emit('responseImg', {
  //       realUrl: realUrl.value,
  //       temUrl: temUrl.value,
  //       fileName: e.file.name,
  //     } as ResImg);
  //   } catch (error) {
  //     console.error('失败', error);
  //   }
  // };
  // 下载图片
  // const handleDownPic = () => {
  // downLoadFile({
  //   fileUrl: props.fileUrl,
  //   fileName: props.fileName || props.fileUrl,
  // }).catch((err) => {
  //   console.log('downloadErr', err);
  // });
  // };
</script>
<style lang="less" scope>
  .df-upload-image {
    width: 80px;
    height: 80px;
    .n-button {
      min-width: auto;
      padding: 0 3px;
    }

    // .n-upload-file-list {
    //   display: none;
    // }

    // .upload-add-img {
    //   width: v-bind(width);
    //   height: v-bind(width);
    //   font-size: 24px;
    //   color: var(--n-text-color);
    //   // border-radius: 3px;
    //   cursor: pointer;
    //   border: var(--n-dragger-border);
    //   border-radius: var(--n-border-radius);
    //   background-color: rgb(250, 250, 252);
    //   display: flex;
    //   align-items: center;
    //   justify-content: center;
    //   transition: border-color 0.3s var(--n-bezier);
    //   &:hover {
    //     border: var(--n-dragger-border-hover);
    //   }
    // }

    .imageclass {
      border-radius: 3px;
      width: v-bind(width);
      height: v-bind(width);
      opacity: 1;
      transition: 0.3s all;
    }
    .notice {
      margin-top: 8px;
      color: #888888;
      font-size: 12px;
    }

    .upload-img {
      width: 100%;
      height: 100%;
      border: 1px solid rgb(224, 224, 230);
      border-radius: var(--n-border-radius);
      &:hover {
        background-color: var(--n-item-color-hover);
        // .icon-img {
        //   // background: var(--n-item-color-hover);
        //   :deep(.n-icon) {
        //     transition: 0.3s all;
        //     opacity: 1;
        //   }
        // }
        .imageclass {
          transition: 0.3s all;
          opacity: 0.12;
        }
      }
    }

    .icon-img {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 100;
      width: v-bind(width);
      height: v-bind(width);
      color: var(--n-text-color);
      border-radius: var(--n-item-border-image-card);
      border: var(--n-item-border-image-card);
    }
  }
</style>

<style lang="less">
  .df-upload-image {
    .n-upload-file--info-status {
      display: none !important;
    }
    .n-upload-file-list .n-upload-file.n-upload-file--image-card-type,.n-upload-trigger.n-upload-trigger--image-card {
      width: 80px;
      height: 80px;
    }
    .n-upload-file-list.n-upload-file-list--grid{
      grid-template-columns:repeat(auto-fill, 80px);
    }
    .upload-img {
      .imageclass {
        img {
          object-fit: cover !important;
        }
      }
      .icon-img {
        .n-icon {
          opacity: 0;
          transition: 0.3s all;
        }
      }
      &:hover {
        .icon-img {
          .n-icon {
            opacity: 1;
            transition: 0.3s all;
          }
        }
      }
    }
  }
</style>
